/**
 * author:Administrator
 * date:2016/3/29
 * desc:TODO
 */
'use strict';

let uuid = require('uuid').v4;
let crypto = require('crypto');

let utils = {};
module.exports = utils;

utils.genToken = function (user) {
  // let str = uuid();
  let str = user.id + '';
  return crypto.createHash('md5').update(str).digest('hex');
};

/**********************************
 *         token 缓存               *
 **********************************/
let __userMap = {};
utils.saveToken = function *(token, user) {
  __userMap[token] = user;
};

// 设定token存放于请求的 headers中
utils.getUser = function *(ctx) {
  let headers = ctx.request.headers;
  let token = headers.token;
  if (!token)return null;
  return __userMap[token];
};
// role 存放于user下
utils.saveRole = function*(ctx, role) {
  let token = ctx.request.headers.token;
  let user = __userMap[token];
  if (user) user.role = role;
  console.log(user);
};
// all role 存放于user下
utils.allRole = function*(ctx, roles) {
  let token = ctx.request.headers.token;
  let user = __userMap[token];
  if (user) user.roles = roles;
};
/**********************************
 *         token 缓存               *
 **********************************/

let request = require('co-request');
let FormatOutput = require('./FormatOutput.js');
let FormatError = require('./FormatError.js');
utils.request = function*(opt) {
  try {
    let retVal = yield request(opt);
    if (retVal.error) return FormatOutput.payloadOrError(null, retVal.error);
    return FormatOutput.fromJson(retVal.body);
  } catch (ex) {
    console.error(ex);
    return FormatOutput.payloadOrError(null, FormatError.E_server_fail);
  }
};